﻿using PDFDesign.Common;
using PDFDesign.Model;
using PDFDesign.Command;
using Newtonsoft.Json.Linq;
using System;
using MahApps.Metro.Controls.Dialogs;
using System.Windows.Input;
using System.Diagnostics;

namespace PDFDesign.ViewModel
{
    public class ViewViewModel : BaseViewModel
    {
        private static readonly object locker = new object();
        private static ViewViewModel viewModel;
        private const string MainUrl = "http://render.silkage.net/render";
        //private const string MainUrl = "http://localhost:2333/render";
        private Random random = new Random();

        private ViewViewModel() { }
        public static ViewViewModel GetInstance()
        {
            if (viewModel == null)
            {
                lock (locker)
                {
                    if (viewModel == null)
                    {
                        viewModel = new ViewViewModel();
                    }
                }
            }
            return viewModel;
        }

        /// <summary>
        /// 默认浏览器打开
        /// </summary>
        public ICommand OpenCommand
        {
            get => new AnotherCommand(_ => Process.Start(Url));
        }

        public void UpdateUrl(string style, string data)
        {
            try
            {
                var request = new RenderRequest { Style = style, Data = data };
                var response = Utils.HttpPost(MainUrl, request.ToString());
                var obj = JObject.Parse(response);
                if (obj["success"].ToString().ToLower() == "true")
                {
                    Url = $"{MainUrl}?key={obj["key"].ToString()}&rn={random.NextDouble()}";
                }
            }
            catch (Exception ex)
            {
                ShowMessage($"预览异常:{ex.Message}");
            }
        }

        private string url = "https://www.wsgjp.com/";
        /// <summary>
        /// 预览地址
        /// </summary>
        public string Url
        {
            get => url;
            set
            {
                url = value;
                OnPropertyChanged("Url");
            }
        }

        /// <summary>
        /// 提示消息
        /// </summary>
        /// <param name="message"></param>
        private void ShowMessage(string message) => DialogCoordinator.Instance.ShowMessageAsync(this, "温馨提示", message, MessageDialogStyle.Affirmative);
    }
}
